<?php

namespace app\api\controller;

use app\api\model\MemberGroupModel;
use app\api\model\MemberInterestClazzModel;
use app\api\model\MemberPaymentModel;
use app\api\model\MemberProCertificationModel;
use app\api\model\NewsModel;
use app\api\model\NewsTimeManageModel;
use app\common\controller\Api;
use app\api\model\MemberModel;
use app\api\model\SmsModel;
use think\Exception;

/**
 * @title 会员
 * @controller api\controller\Member
 * @group base
 */
class Member extends Api
{
    /**
     * @title  会员首页
     * @url /api/Member/MemberIndex
     * @method GET
     * @return name:data type:array ref:definitions\dictionary
     */
    function memberIndex(){
        $this->success("成功");
    }

    /**
     * @title 会员登录（账号密码）
     * @url /api/Member/login
     * @method POST
     * @param  name:username type:String require:1 desc:用户名
     * @param  name:password type:String require:1 desc:密码
     * @return name:data type:array ref:definitions\dictionary
     */
    public function login()
    {
        $data = \input("post.");
        try {
            $MemberModel = new MemberModel();
            $result = $MemberModel->MemberPasswordLogin($data['username'],$data['password']);
            $this->success($result['msg'],$result);
        }catch (Exception $e){
            $this->error("登录异常");
        }
    }

    /**
     * @title  获取会员信息
     * @url /api/Member/getMemberInfo
     * @method GET
     * @param name:token type:String require:1 desc:token
     * @return name:data type:array ref:definitions\dictionary
     */
    public function getMemberInfo(){
        $MemberModel = new MemberModel();
        $member = $MemberModel->getMemberInfo($this->request->get("token"));
        if($member!=null){
            $this->success("获取成功",$member);
        }else{
            $this->error("获取失败");
        }
    }

    /**
     * @title  会员登录或注册（手机号）
     * @url /api/Member/loginorregister
     * @method POST
     * @param  name:mobile type:Int require:1 desc:电话号码
     * @param  name:smsCode type:Int require:1 desc:短信验证码
     * @return name:data type:array ref:definitions\dictionary
     */
    public function loginorregister(){
        try {
            $data = input("post.");
            $MemberModel = new MemberModel();
            $member = $MemberModel->findMemberMobile($data['mobile']);
            if($member){
                //登录
                $smsModel = new SmsModel();
                $sms = $smsModel->getSmsByMobile($data['mobile']);
                if($sms['times']>0){
                    $this->error("验证码已使用");
                }
                if ($data['smsCode'] == $sms['code']) {
                    //登录
                    $flag = $MemberModel->MemberLogin($member);
                    if($flag){
                        $member = $MemberModel->findMemberMobile($data['mobile']);
                        //更新验证码使用次数
                        $smsModel->saveCodeTimes($data['smsCode']);
                        $result = ['token'=>$member['token']];
                        $this->success("登录成功",$result);
                    }else{
                        $this->error("登录失败");
                    }
                }else{
                    $this->error("验证码过期");
                }
            }else{
                //手机注册
                $smsModel = new SmsModel();
                $sms = $smsModel->getSmsByMobile($data['mobile']);
                if($sms['times']>0){
                    $this->error("验证码已使用");
                }
                if($data['smsCode']==$sms['code']){
                    //注册
                    $user = $MemberModel->MemberRegister($data['mobile']);
                    //输出token
                    if(!empty($user)&&$user!=false){
                        //更新验证码使用次数
                        $smsModel->saveCodeTimes($data['smsCode']);
                        $result = [
                            'token'=>$user,
                        ];
                        $this->success("注册成功",$result);
                    }else{
                        $this->success("注册失败");
                    }
                }else{
                    $this->error("验证码过期");
                }
            }
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title  关注用户
     * @url /api/Member/focusMember
     * @method GET
     * @param name:token type:String require:1 desc:token
     * @param name:focusUid type int require:1 desc:被关注者uid
     * @return name:data type:array ref:definitions\dictionary
     */
    public function focusMember(){
        $memberModel = new MemberModel();
        $flag = $memberModel->focusMember($this->request->get("token"),$this->request->get()['focusUid']);
        if($flag){
            $this->success("关注成功");
        }else{
            $this->error("关注失败");
        }
    }

    /**
     * @title  获取关注的用户
     * @url /api/Member/getFocusMember
     * @method GET
     * @param name:token type:String require:1 desc:
     * @return name:data type:array ref:definitions\dictionary
     */
    public function getFocusMember(){
        //关注用户
        $memberModel = new MemberModel();
        $focusArr = $memberModel->getFocusMember($this->request->get("token"));
        $this->success("获取成功",$focusArr);
    }

    /**
     * @title 提交用户资料
     * @url /api/Member/saveMemberInfo
     * @method POST
     * @param name:token type:string require:1 desc:token
     * @param name:labels type:string desc:兴趣标签组，“,”分割栏目标签
     * @param name:username type:string desc:用户名
     * @param name:avar type:string desc:用户头像路径
     * @return name:data type:array ref:definitions\dictionary
     */
    public function saveMemberInfo(){
        try {
            $data = input("post.");
            //token保存用户信息
            $memberModel = new MemberModel();
            $member = $memberModel->findMemberByToken($data['token']);
            if($member!=null){
                //保存用户数据
                $flag = $memberModel->saveMemberInfo($data);
                if($flag){
                    $this->success("保存成功");
                }else{
                    $this->error("保存失败");
                }
            }else{
                $this->error("用户不存在");
            }
        }catch (Exception $e){
            $this->error("保存异常");
        }
    }

    /**
     * @title  修改用户密码
     * @url /api/Member/modifyMemberPassword
     * @method POST
     * @param name:password type:String require:1 desc:密码
     * @param name:mobile type:String require:1 desc:手机号码
     * @param name:smscode type:String require:1 desc:手机验证码
     * @return name:data type:array ref:definitions\dictionary
     */
    public function modifyMemberPassword(){
        try{
            $data = input("post.");
            //验证手机验证码
            $smsModel = new SmsModel();
            $sms = $smsModel->getSmsByMobile($data['mobile']);
            if($sms!=null){
                if($sms['times']>0){
                    $this->error("验证码已使用");
                }
                if($sms['code']!=$data['smscode']){
                    $this->error("验证码错误");
                }
            }
            $memberModel = new MemberModel();
            //修改用户密码
            $flag = $memberModel->modifyPassword($data);
            if($flag){
                $this->success("修改成功");
            }else{
                $this->error("修改失败");
            }
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title  检查用户名是否存在
     * @url /api/Member/checkusername
     * @method POST
     * @param name:token type:String require:1 desc:
     * @param name:username type:String require:1 desc:用户名
     * @return name:data type:array ref:definitions\dictionary
     */
    public function checkusername(){
        try{
            $data = input("post.");
            if(empty($data['username'])){
                $this->error("用户名不能为空");
            }
            $memberModel =  new MemberModel();
            $flag = $memberModel->checkUsername($data);
            if($flag==1){
                $this->error("用户名已存在");
            }else if($flag==-1){
                $this->success("用户名可用");
            }else{
                $this->error("接口异常");
            }

        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 用户兴趣标签推荐文章
     * @url /api/Member/memberecommendnews
     * @method GET
     * @param name:token type:string require:1 desc:token
     * @return name:data type:array ref:definitions\dictionary
     */
    public function memberecommendnews(){
        try {
            //获取用户兴趣标签
            $memberModel = new MemberModel();
            $member = $memberModel->findMemberByToken($this->token);
            $memberInterestClazzModel = new MemberInterestClazzModel();
            $interest = $memberInterestClazzModel->getMemberInterestClazz($member['userid']);
            //获取标签所属文章
            $newsModel = new NewsModel();
            $news = $newsModel->BatchgetNews($interest['clazzids']);
            $this->success("获取成功",$news);
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 记录用户付费信息
     * @url /api/Member/ispaymember
     * @method POST
     * @param name:userid type:int require:1 desc:用户id
     * @param name:newsid type:int desc:用户购买文章时需要提交
     * @param name:goodstype type:int require:1 desc:商品类型1:文章，2：付费用户
     * @param name:order type:string require:1 desc:订单号
     * @param name:wxorder type:string require:1 desc:微信订单号
     * @param name:state type:int require:1 desc:支付状态0：未支付，-1：支付失败，1支付成功
     * @return name:data type:array ref:definitions\dictionary
     */
    public function ispaymember(){
        try {
            $data = input("post.");
            //存储用户下单信息
            $memberPaymentModel = new MemberPaymentModel();
            $flag =$memberPaymentModel->saveMemberPayment($data);
            if($flag){
                $this->success("保存成功");
            }else{
                $this->error("保存失败");
            }
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 用户发送帖子
     * @url /api/Member/membersendnews
     * @method GET
     * @param name:token type:string require:1 desc:token
     * @param name:bclassid type:int require:1 desc:父类id
     * @param name:classid type:int require:1 desc:子类id
     * @param name:title type:int require:1 desc:标题
     * @param name:titlepic type:int require:1 desc:图片地址
     * @param name:newstext type:int require:1 desc:内容
     * @return name:data type:array ref:definitions\dictionary
     */
    public function membersendnews(){
        try {
            //插入文章表
            $data = input("post.");
            if(empty($data['title'])){
                $this->error("标题不能为空");
            }else if(empty($data['smalltext'])){
                $this->error("文章内容不能为空");
            }else{
                $data['userid'] = $this->userid;
                $data['username'] = $this->username;
                $newModel = new NewsModel();
                $flag = $newModel->saveNews($data);
                if($flag){
                    $this->success("审核中");
                }else{
                    $this->error("发帖失败");
                }
            }
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 获取用户发布的文章
     * @url /api/Member/getMemberNews
     * @method GET
     * @param name:token type:string require:1 desc:token
     * @return name:data type:array ref:definitions\dictionary
     */
    public function getMemberNews(){
        try {
            //获取用户发布的文章列表
            $newModel = new NewsModel();
            $memberNew = $newModel->getMemberNews($this->userid);
            $this->success($memberNew);
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 用户申请专家
     * @url /api/Member/isProCertification
     * @method GET
     * @param name:token type:string require:1 desc:token
     * @param name:remark type:string require:1 desc:申请理由
     * @return name:data type:array ref:definitions\dictionary
     */
    public function isProCertification(){
        try {
         $data = input("post.");
         //查询userid
         $memberModel = new MemberModel();
         $member = $memberModel->findMemberByToken($data['token']);
         $proModel = new MemberProCertificationModel();
         $flag = $proModel->applicationProCertification($member['userid'],$data['remark']);
         if($flag){
            $this->success("等待审核");
         }else{
             $this->error("申请失败");
         }
        }catch (Exception $e){
          $this->error("接口异常");
        }
    }

    /**
     * @title 专家发帖
     * @url /api/Member/proCertificationSendNews
     * @method POST
     * @param name:token type:string require:1 desc:token
     * @param name:bclassid type:int require:1 desc:父类id
     * @param name:classid type:int require:1 desc:子类id
     * @param name:title type:int require:1 desc:标题
     * @param name:newstext type:int require:1 desc:内容
     * @param name:darenbi type:int require:1 desc:达人币
     * @param name:topType type:string require:1 desc:排行类型id逗号间隔','
     * @return name:data type:array ref:definitions\dictionary
     */
    public function proCertificationSendNews(){
        try {
            //检查是否是专家用户组
            $memberModel = new MemberModel();
            $member = $memberModel->findMemberByToken($this->token);

            if($member['groupid']!=3){
                $this->error("该用户不是专家");
            }else{
                //插入文章表
                //通知到kaijiang端
                $data = input("post.");

                //判断是否是禁止发帖时段
                $timeManageModel = new NewsTimeManageModel();
                $timeManageInfo = $timeManageModel->getTimeManage($data['classid']);
                if($timeManageInfo!=null){
                    //获取当前时间段
                    $NowTimeSecond = strtotime(date("H:i",time()));
                    $prohibitbegintimeSecond = strtotime($timeManageInfo['prohibitbegintime']);
                    $prohibitendtimeSecond = strtotime($timeManageInfo['prohibitendtime']);

                    if($NowTimeSecond>=$prohibitbegintimeSecond
                        ||$NowTimeSecond<=$prohibitendtimeSecond){
                        $this->error("此时间段内禁止发帖");
                    }
                }

                if(empty($data['title'])){
                    $this->error("标题不能为空");
                }else if(empty($data['newstext'])){
                    $this->error("文章内容不能为空");
                }
                //判断排行分类是否为空
//                if(count($data['topType'])==0){
//                    $this->error("排行分类不能为空");
//                }
                $data['userid'] = $this->userid;
                $data['username'] = $this->username;
                $data['ispro'] = 1;

                $newsModel = new NewsModel();
                $flag= $newsModel->saveNews($data);
                if($flag){
                    $this->success($flag);
                }else{
                    $this->error("发布失败");
                }
            }
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 获取用户所在用户组
     * @url /api/Member/getMemberGroup
     * @method GET
     * @param name:token type:string require:1 desc:token
     * @return name:data type:array ref:definitions\dictionary
     */
    public function getMemberGroup(){
        try {
            $memberModel = new MemberModel();
            $member = $memberModel->findMemberByToken($this->token);

            $memberGroupModel = new MemberGroupModel();
            $group = $memberGroupModel->getGroup($member['groupid']);
            $this->success("获取成功",$group);
        }catch (Exception $e){
            $this->error("接口异常");
        }

    }

    /**
     * @title 判断用户是否选择兴趣标签
     * @url /api/Member/isMemberInterestClazz
     * @method POST
     * @param name:token type:file desc:token
     * @return name:data type:array ref:definitions\dictionary
     */
    public function isMemberInterestClazz(){
        try {
           $memberModel = new MemberModel();
           $member = $memberModel->findMemberByToken($this->token);
           $interestModel = new MemberInterestClazzModel();
           $flag = $interestModel->isMemberInterestClazz($member['userid']);
           if($flag){
               $this->success("已有兴趣标签");
           }else{
               $this->error("未关注兴趣标签");
           }
        }catch (Exception $e){
            $this->error("接口异常");
        }
    }

    /**
     * @title 上传用户头像
     * @url /api/Member/uploadAvatar
     * @method POST
     * @param name:avatar type:file desc:头像文件
     * @return name:data type:array ref:definitions\dictionary
     */
    public function uploadAvatar(){

        $img = $this->request->file("avatar");

        $info = $img->move("../public/uploads");

        $url = $info->getSaveName();

        if($url!=""){
            //保存到用户信息中
            $MemberModel = new MemberModel();
            $member = $MemberModel->findMemberByToken($this->request->post("token"));
            $member['avatar'] = "uploads/".$url;
            $MemberModel->save($member,"id = {$member['id']}");
        }

        $result = [
            'url'=>"uploads/".$url,
        ];

        $this->success("保存成功",$result);
    }

    /**
     * @title 测试接口
     * @url /api/Member/test
     * @method GET
     * @return name:data type:array ref:definitions\dictionary
     */
    public function test(){

        //判断是否是禁止发帖时段
        $timeManageModel = new NewsTimeManageModel();
        $timeManageInfo = $timeManageModel->getTimeManage(17);
        //获取当前时间段
        $time = date("H:i",time());
        $NowTimeSecond = strtotime(date("H:i",time()));
        $prohibitbegintimeSecond = strtotime($timeManageInfo['prohibitbegintime']);
        $prohibitendtimeSecond = strtotime($timeManageInfo['prohibitendtime']);



        $this->success("获取成功",$timeManageInfo);
    }

}